﻿/*
*VMukti -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, VMukti Solutions Pvt. Ltd.
*
* Hardik Sanghvi <hardik@vmukti.com>
*
* See http://www.vmukti.com for more information about
* the VMukti project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
using System;
using System.IO;
using System.Text;
using uno.util;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.util;
using VMukti.Bussiness.WCFServices.BootStrapServices.BasicHttp;
using VMuktiAPI;
using VMuktiService;

namespace VMukti.Presentation.Domains
{
    class clsPresentationUpload:IDisposable
    {
        #region Uploading Recorded Files

        System.IO.FileStream fsR;
        int flag = 0;

        int nosignal = 0;
        double smallPart;
        byte[] arr = new byte[5000];
        byte[] Larr;

        #endregion

        object objHttpPresentation = null;

        //private static string FileName = @"C:\Presentations\Presentationnew.ppt";

        public unoidl.com.sun.star.beans.PropertyValue aArgs;

        public clsPresentationUpload()
        {
            try
            {
                objHttpPresentation = new HttpPresentationUploadDelegates();

                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpJoin += new HttpPresentationUploadDelegates.DelsvcHttpJoin(Window1_EntsvcHttpJoin);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpSendUploadedFile += new HttpPresentationUploadDelegates.DelsvcHttpSendUploadedFile(Window1_EntsvcHttpSendUploadedFile);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpUnJoin += new HttpPresentationUploadDelegates.DelsvcHttpUnJoin(Window1_EntsvcHttpUnJoin);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpGetPresentationName += new HttpPresentationUploadDelegates.DelsvcHttpGetPresentationName(Window1_EntsvcHttpGetPresentationName);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpSlidesCount += new HttpPresentationUploadDelegates.DelsvcHttpSlidesCount(clsPresentationUpload_EntsvcHttpSlidesCount);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpGetSlideStream += new HttpPresentationUploadDelegates.DelsvcHttpGetSlideStream(clsPresentationUpload_EntsvcHttpGetSlideStream);
                ((HttpPresentationUploadDelegates)objHttpPresentation).EntsvcHttpPPTExists += new HttpPresentationUploadDelegates.DelsvcHttpPPTExists(clsPresentationUpload_EntsvcHttpPPTExists);

                BasicHttpServer bhsPresentation = new BasicHttpServer(ref objHttpPresentation, "http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "80/PresentationUpload");
                bhsPresentation.AddEndPoint<IHttpPresentationUploadService>("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":80/PresentationUpload");
                bhsPresentation.OpenServer();

                
                
            }
            catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "clsPresentationUpload()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        bool clsPresentationUpload_EntsvcHttpPPTExists(string filename)
        {   try
            {
                return Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + filename);
            }
		catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "clsPresentationUpload_EntsvcHttpPPTExists()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return false;
            }
        }

        Stream clsPresentationUpload_EntsvcHttpGetSlideStream(byte[] barr)
        {
            try
            {
            //MemoryStream ms = new MemoryStream(ConvertStreamToByteBuffer(sArgs));
            //ms.Position = 0;
            ////byte[] newbar = new byte[ms.ToArray().Length - 1];
            ////ms.Read(newbar, 0, ms.ToArray().Length - 1);

            //byte[] newbar = new byte[ms.ToArray().Length-1];
            //ms.Read(newbar, 0, ms.ToArray().Length-1);

            //string PName = Encoding.ASCII.GetString(newbar);

            ////string PName = Convert.ToString(ms.ToArray()[0]);
            //int count = Convert.ToInt32(ms.ToArray()[ms.ToArray().Length-1]);


            byte[] newbar = new byte[barr.Length - 1];
            for (int i = 0; i < barr.Length - 1; i++)
            {
                newbar[i] = barr[i];
            }
            //ms.Read(newbar, 0, barr.Length - 2);


            string PName = Encoding.ASCII.GetString(newbar);

            //string PName = Convert.ToString(ms.ToArray()[0]);
            int count = Convert.ToInt32(barr[barr.Length - 1]);

            string[] strTemp = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + PName, "*.jpg");
            FileStream fs = File.Open(strTemp[count], FileMode.Open, FileAccess.Read);
            MemoryStream mms = new MemoryStream(ConvertStreamToByteBuffer(fs));
            fs.Close();
            fs.Dispose();
            return mms;
            }
			catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "clsPresentationUpload_EntsvcHttpGetSlideStream()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }

        int clsPresentationUpload_EntsvcHttpSlidesCount(string PName)
        {   try
            {
            // return Directory.GetFiles("C:\\Presentations\\" + PName).Length;
            //return Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Default Company Name\\VMukti\\Adiance\\Presentations\\" + PName, "*.jpg").Length;
                return Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + PName, "*.jpg").Length;
            }
		catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "clsPresentationUpload_EntsvcHttpSlidesCount()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return -1;
            }
        }

        string[] Window1_EntsvcHttpGetPresentationName()
        {
            //string path=Environment.SpecialFolder.ProgramFiles.ToString() + "\\Default Company Name\\VMukti\\Adiance\\Presentations";
            try
            {
            //string[] dirName = Directory.GetDirectories((Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)).ToString() + "\\Default Company Name\\VMukti\\Adiance\\Presentations");
                string[] dirName = Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\");
            string[] dirNamenew = new string[dirName.Length];
            for (int i = 0; i < dirName.Length; i++)
            {
                string[] temp = dirName[i].Split('\\');
                dirNamenew[i] = temp[temp.Length - 1];
            }

            return dirNamenew;
            }
			catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "Window1_EntsvcHttpGetPresentationName()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }

        void Window1_EntsvcHttpUnJoin()
        {

        }

        void Window1_EntsvcHttpSendUploadedFile(string strFileName, byte[] bytearr, int intSig)
        {
            try
            {
                DirectoryInfo di = null;
                if (fsR == null && flag == 0 && nosignal == 0)
                {
                    string[] strTemp = strFileName.Split('\\');

                    //if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Default Company Name\\VMukti\\Adiance\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim()))
                    //{
                    //    System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity();
                        
                    //    di = Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Default Company Name\\VMukti\\Adiance\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim(), new System.Security.AccessControl.DirectorySecurity("", System.Security.AccessControl.AccessControlSections.All));
                    //}

                    if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim()))
                    {
                        //System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity();

                        di = Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim());
                    }

                    fsR = new System.IO.FileStream(di.FullName + "\\" + strTemp[strTemp.Length - 1], System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    fsR.Close();
                    fsR = File.OpenWrite(di.FullName + "\\" + strTemp[strTemp.Length - 1]);
                    fsR.Position = fsR.Length;
                    fsR.Write(bytearr, 0, bytearr.Length);
                    fsR.Close();
                    if (intSig == 1)
                    {
                        fsR.Dispose();
                        fsR = null;
                        nosignal = 0;
                    }

                }
                else if (fsR != null && flag == 0)
                {
                    string[] strTemp = strFileName.Split('\\');



                    //if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Default Company Name\\VMukti\\Adiance\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim()))
                    //{
                    //    di = Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\Default Company Name\\VMukti\\Adiance\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim());
                    //}

                    if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim()))
                    {
                        di = Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim());
                    }
                    else
                    {
                        di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + strTemp[strTemp.Length - 1].Replace(".ppt", "").Trim());
                    }

                    fsR = File.OpenWrite(di.FullName + "\\" + strTemp[strTemp.Length - 1]);

                    fsR.Position = fsR.Length;
                    fsR.Write(bytearr, 0, bytearr.Length);
                    fsR.Close();

                    //convert the ppt to jpg using openoffice

                    if (intSig == 1)
                    {
                        XComponentContext localContext = Bootstrap.bootstrap();

                        XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)localContext.getServiceManager();

                        XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
                        string strpath = di.FullName + "\\" + strTemp[strTemp.Length - 1];
                        string newstr = strpath.Replace('\\', '/');
                        XComponent xComponent = componentLoader.loadComponentFromURL("file:///" + newstr, "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[1] { MakePropertyValue("Hidden", new uno.Any(true)) });

                        int newslide = ((unoidl.com.sun.star.drawing.XDrawPagesSupplier)xComponent).getDrawPages().getCount();

                        int nHighestPageNumber = newslide - 1;

                        DeleteAllPagesExcept(xComponent, 0);
                        string path = di.FullName.Replace('\\', '/');
                        string cNewName = "file:///" + newstr;

                        ((XStorable)xComponent).storeToURL(cNewName + ".html", new unoidl.com.sun.star.beans.PropertyValue[1] { MakePropertyValue("FilterName", new uno.Any("impress_html_Export")) });

                        ((XCloseable)xComponent).close(true);

                        xComponent.dispose();

                        fsR.Dispose();
                        fsR = null;
                        string[] strFiles = Directory.GetFiles(di.FullName, "*.html");
                        for (int j = 0; j < strFiles.Length; j++)
                        {
                            File.Delete(strFiles[j]);
                        }
                        string[] strJpg = Directory.GetFiles(di.FullName, "*.jpg");

                        for (int k = 0; k < strJpg.Length; k++)
                        {

                            FileInfo f = new FileInfo(strJpg[k]);
                            string strName = "";
                            string newstr1 = "";
                            if (f.Name.Split('.')[0].Length < 5)
                            {
                                strName = f.Name.Replace("img", "Slide0");
                                newstr1 = strJpg[k].Replace(f.Name, "");
                                File.Move(strJpg[k], newstr1 + strName);
                            }
                            else
                            {
                                strName = f.Name.Replace("img", "Slide");
                                newstr1 = strJpg[k].Replace(f.Name, "");
                                File.Move(strJpg[k], newstr1 + strName);
                            }

                        }

                        nosignal = 0;
                        intSig = 0;
                    }
                }
            }
			catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "Window1_EntsvcHttpSendUploadedFile()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
              
            }
        }

        void Window1_EntsvcHttpJoin()
        {

        }

        public void DeleteAllPagesExcept(object oDoc, object nPageToKeep)
        {
            try
            {
            int nNumPages = ((unoidl.com.sun.star.drawing.XDrawPagesSupplier)oDoc).getDrawPages().getCount();
            int nHighestPageNumber = nNumPages - 1;

            // Delete the last page, then the page before that,
            // then the page before that, until we get to the
            // page to keep.
            // This deletes all pages AFTER the page to keep.
            int nPageToDelete = nHighestPageNumber;
            while (nPageToDelete > (int)nPageToKeep)
            {
                // Get the page.
                object oPage = ((unoidl.com.sun.star.drawing.XDrawPagesSupplier)oDoc).getDrawPages().getByIndex(nPageToDelete);

                // Tell the document to remove it.              

                //((unoidl.com.sun.star.drawing.XDrawPagesSupplier)oDoc).getDrawPages().remove((unoidl.com.sun.star.drawing.XDrawPage)oPage);

                nPageToDelete = nPageToDelete - 1;
            }

            // Delete all the pages before the page to keep.
            for (int i = 0; i <= (int)nPageToKeep - 1; i++)
            {
                // Delete the first page.
                nPageToDelete = 0;
                // Get the page.
                object oPage = ((unoidl.com.sun.star.drawing.XDrawPagesSupplier)oDoc).getDrawPages().getByIndex(nPageToDelete);
                // Tell the document to remove it.
                //((unoidl.com.sun.star.drawing.XDrawPagesSupplier)oDoc).getDrawPages().remove((unoidl.com.sun.star.drawing.XDrawPage)oPage);

            }
            }
			catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "DeleteAllPagesExcept()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
              
            }
        }

        private unoidl.com.sun.star.beans.PropertyValue MakePropertyValue(string p, uno.Any p_2)
        {   try
            {
            aArgs = new unoidl.com.sun.star.beans.PropertyValue();
            aArgs.Name = p;
            aArgs.Value = p_2;
            return aArgs;
            }
		catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "MakePropertyValue()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
              
            }
        }

        private byte[] ConvertStreamToByteBuffer(Stream stream)
        {
            try
            {
                int num;
                MemoryStream tempStream = new MemoryStream();

                while ((num = stream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)num));
                }
              
                return tempStream.ToArray();
           }
			catch (System.Exception ex)
            {
                ex.Data.Add("My Key", "ConvertStreamToByteBuffer()--:--clsPresentationUpload.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
              return null;
            }
        }

        ~clsPresentationUpload()
        {
            Dispose();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if(fsR!=null)
            {
                fsR=null;
            }
            if(objHttpPresentation!=null)
            {
                objHttpPresentation=null;
            }
            if (aArgs != null)
            {
                aArgs = null;
            }
        }

        #endregion
    }
}
